$(function() {
	var findTarget = function(target) {
		target = $(target);
		if (target.closest('#J_Panel').length) {
			if (target.is('div')) {
				return {
					td: target.parent(),
					div: target
				};
			} else if (target.is('td')) {
				var div = target.children('div').focus();
				if (div.length) {
					return {
						td: target,
						div: target.children('div')
					};
				}
			}
		}
		return target;
	},
	wrap = function(text) {
		return $('<div>', {
			contentEditable: true
		}).text(text);
	},
	showTip = function(text) {
		var tip = $('#J_Tip');
		tip.data('timeout') && clearTimeout(tip.data('timeout'));
		tip.text(text).css('visibility', 'visible').data('timeout', setTimeout(function() {
			tip.css('visibility', 'hidden');
		}, 3000));
	},
	getData = function() {
		var rows = table[0].rows,
		row = rows.length - 1,
		col = rows[0].cells.length - 1,
		line = rows[0],
		reg = /^\w+$/,
		locales = [],
		data = {},
		text, i, j;
		for (i = 1; i < col; i++) {
			text = $(line.cells[i]).text();
			locales.push(text);
			if (reg.test(text)) {
				data[text] = {};
			}
		}
		for (i = 1; i < row; i++) {
			line = rows[i];
			text = $(line.cells[0]).text();
			for (j = 1; j < col; j++) {
				if (reg.test(locales[j - 1]) && reg.test(text)) {
					data[locales[j - 1]][text] = $(line.cells[j]).text();
				}
			}
		}
		return data;
	},
	loadData = function() {
		table.html('');
		$.get('/json', { _: new Date().getTime() }, function(data) {
			var row = table[0].insertRow(0),
			fields, i, j = 1, k = 1, l;
			row.className = 'head';
			$(row.insertCell(0)).addClass('field disable save').text('Save');
			for (i in data) {
				$(row.insertCell(j++)).html(wrap(i));
			}
			$(row.insertCell(j++)).addClass('disable append column').width(20).text('+');
			if (i) {
				fields = data[i];
				for (i in fields) {
					l = 1;
					row = table[0].insertRow(k++);
					$(row.insertCell(0)).addClass('field').html(wrap(i));
					for (j in data) {
						$(row.insertCell(l++)).html(wrap(data[j][i].message));
					}
				}
			}
			row = table[0].insertRow(k++);
			$(row.insertCell(0)).addClass('field disable append').text('+');
		});
	},
	clickHandle = function(evt) {
		var target = findTarget(evt.target),
		rows = table[0].rows,
		col, row, i;
		if (target.td && !target.td.hasClass('edit')) {
			lastEdit && lastEdit.removeClass('edit');
			lastEdit = target.td.addClass('edit');
		} else if (!target.td) {
			lastEdit && lastEdit.removeClass('edit');
			if (target.hasClass('append')) {
				col = rows[0].cells.length - 1;
				row = rows.length - 1;
				if (target.hasClass('column')) {
					for (i = 0; i < row; i++) {
						$(rows[i].insertCell(col)).html(wrap(''));
					}
				} else {
					row = table[0].insertRow(row);
					$(row.insertCell(0)).addClass('field').html(wrap(''));
					for (i = 1; i < col; i++) {
						$(row.insertCell(i)).html(wrap(''));
					}
				}
			} else if (target.hasClass('save')) {
				var pData = getData();
				for (i in pData) {
					$.post('/' + i, pData[i], function(result) {
						if (result != 'success') {
							showTip('Save failed');
						}
					});
				}
				showTip('Saved successfully');
			}
		}
	},
	table = $('#J_Panel'),
	oPath = $('#J_Path input').blur(function() {
		if (oPath.val() != oPath.data('path')) {
			$.post('/config', { path: oPath.val() }, loadData);
			localStorage.setItem('path', oPath.val());
		}
		oPath.data('path', oPath.val());
	}),
	lastEdit;
	$('html').click(clickHandle);
	if (localStorage.getItem('path')) {
		oPath.val(localStorage.getItem('path')).blur();
	} else {
		loadData();
		$.get('/config', function(result) {
			oPath.val(result.path);
		});
	}
});
